<template>
	<view class="base-resource-detail">
		<view v-if="!tabVisible" class="left-icon">
			<navSearchBar  :zIndex="titleZindex" background="" :initEenter="initEenter"></navSearchBar>
		</view>
		<view v-if="tabVisible" class="top-operate">
			<navSearchBar  :title="baseName"  :zIndex="titleZindex" :initEenter="initEenter"></navSearchBar>
			<view class="top-operate-tab" :style="{zIndex:titleZindex}">
				<tn-tabs  :list="tabList" :isScroll="false" height="88" :current="current" name="tab-name" :bold="true" activeColor="#000000" inactiveColor="#5B5D65" @change="changeTab" :barWidth="60" :barHeight="4"></tn-tabs>
			</view>
		</view>
		<scroll-view  class="custom-tabbar-page" scroll-y enable-back-to-top >
			
				
				
				<image class="title-picture" :src="bgImage" mode="widthFix"></image>
				<view class="body-field">
					<view  class="title-card" >
						<view class="name-field">
							<text class="name">{{baseName}}</text>
							<view class="right-type">
								<image src="/static/icon/union.png" mode=""></image>
								<text >{{typeName}}</text>
							</view>
						</view>
					
						<view class="detail-field" >
							<view class="video" v-if="videoUrl">
								<!-- https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4 -->
								<video id="myVideo" :src="videoUrl"
								    @error="videoErrorCallback"   controls></video>
							</view>
							<view class="sort-title" v-if="shortTitle"><text>{{shortTitle}}</text></view>
							<view class="text-field text-style" v-if="description">
								<text>{{description}}</text>
							</view>
							<view class="module-field">
								<view v-for="(item,index) in moduleData" :key="index" class="module-item">
									<text class="tn-icon-tag"></text><text>{{item.title}}</text>
								</view>
							</view>
								
								
						
						</view>
					</view>
					<view  class="introduce-card" >
						<view class="title">
							<text>产品特色</text>
						</view>
						
						<view class="text-field text-style">
							<text>{{feature}}</text>
							
						</view>
					</view>
					<view class="nearby-card">
						<view class="title">
							
							<text >产品内容</text>
						</view>
						<view class="list">
							<my-rich-text :htmlContent="content"></my-rich-text>
						</view>
					</view>
				</view>
			
		</scroll-view>
		<wx-share ref="share"></wx-share>
		<view  v-if="visibleByAdmin">
			<my-guide-nav iconMargin="78rpx" :navOptions="navOptions" :buttonOptions="customButtonGroups"  @buttonClick="onButtonClick" @textClick="onOptionClick"></my-guide-nav>
		</view>
		<view v-else>
			<userGuideNav  :userInfo="contactInfo"></userGuideNav>
		</view>
	</view>
</template>

<script>
	import {USER_INFO,ROLE_TYPE} from '@/common/util/constants.js';
	import userGuideNav from '../common/user-guide-nav.vue';
	import {throttle} from "@/common/util/util";
	import pageShowOrHideMixin from '@/common/mixin/pageShowOrHideMixin';
	export default {
		mixins:[pageShowOrHideMixin],
		components:{
			userGuideNav
		},
		data() {
			return {
				initEenter:false,
				roleType:ROLE_TYPE.COMMON,
				contactInfo:{},
				titleZindex:100,
				tabList: [
					{
					  'tab-name': '产品简介'
					}
					,{
					 'tab-name': '产品特色',
					}
					, {
					 'tab-name': '产品内容',
					 
					}
				],
				current: 0,
				moduleData:[],
				videoUrl:'',
				feature:'',
				shortTitle:'',
				description:'',
				bgImage:'',
				tabVisible:false,
				baseName:'',
				typeName:'',
				cooperationLevel:'',
				starLevel:3,
				simpleAddress:'',
				detailAddress:'skj案说法就是雷锋精神独立房间急急急急急急',
				content:'',
				navOptions:[
					{
					icon: 'star',
					text: '收藏',
					iconColor:'#656371',
					fontColor:'#656371',
					imgUrl:'/static/icon/collect.png'
				  },{
					icon: 'write',
					text: '标注',
					iconColor:'#656371',
					fontColor:'#656371',
					imgUrl:'/static/icon/label.png',
				  },
				  {
					icon: 'write',
					text: '购物',
					iconColor:'#656371',
					fontColor:'#656371',
					imgUrl:'/static/icon/shop.png',
				  },
				  ],
				customButtonGroups:[
					{
					text: '分享海报',
					bgColor: '#F48C2B',
					icon:'tn-icon-send',
					color: '#FFFFFF',
					imgUrl:'/static/icon/poster.png'
				  },
				  {
					text: '分享产品',
					backgroundColor: '#05C160',
					icon:'tn-icon-send',
					color: '#FFFFFF',
					imgUrl:'/static/icon/share.png'
				  }],
				  nearbyList:[{
					  title:'jfjslf舒服实',
					  piture:'../../../static/wx.png',
					  detailAddress:'是否是咖啡呃呃呃呃呃呃呃呃烦烦烦是放假放假我',
					  distance:'2'
					  
				  }],
				  currentPath:'',
				
			}
		},
		computed:{
			visibleByAdmin(){
				return this.roleType == ROLE_TYPE.ADMIN;
			}
		},
		onShareAppMessage(object){
			console.log('onShareAppMessage',object)
			return {
			      title: this.baseName+'—精选产品',
			      path: this.currentPath,
			      
			    }
		},
		onShareTimeline(object){
			console.log('onShareTimeline',object)
		},
		onLoad(e){
			console.log('productore detail onload',e,this.$Route.query)
			this.baseId = this.$Route.query.id;
			let role_id;
			let userInfo = uni.getStorageSync(USER_INFO);
			let shareId;
			if(userInfo) {
				role_id = userInfo.role_id;
				this.userId = userInfo.id;
			}
			//若小程序活跃 进入分享会走这里但是页面只有一个,启动参数path也不是detail
			if(e&&e.id){
				this.baseId = e.id;
			}
			if(e&&e.scene){//扫码，如果扫码人已经打开过该app会走这
				let scene = decodeURIComponent(e.scene)
				let relist = scene.match(/id=(.*)/)
				console.log('options',relist)
				let sceneId;
				if(relist[1]){
					sceneId = relist[1];
				}
				this.baseId = sceneId;
			}
			if(e && e.user_id){//用户先点开一个人的分享已经启动该app，在点开另一个的分享，就会走这不会走下面启动参数还是之前的
				shareId = e.user_id;
			}
			let launchOptions = uni.getLaunchOptionsSync();
			let pages = getCurrentPages();
			if(!this.baseId &&launchOptions.path == "pages/product/detail"){
				
				
				if(launchOptions.query.id || launchOptions.query.scene){
					////从分享得地方启动得 或扫码
					let sceneId;
					if(launchOptions.query.scene) {
						let scene = decodeURIComponent(launchOptions.query.scene)
						let relist = scene.match(/id=(.*)/)
						console.log(relist)
						if(relist[1]){
							sceneId = relist[1];
						}
					}
					if(pages.length == 1){
						this.baseId = launchOptions.query.id || sceneId;
						this.initEenter = true;
						shareId = launchOptions.query.user_id;
					}
				} else {
					this.$tip.alert('传参无效')
				}
			}
			
			// console.log(decodeURIComponent(e.query))
			console.log('productore detail',role_id,this.roleType,)
			
			console.log('curpage', pages.length)
			console.log('productore getLaunchOptionsSync',launchOptions)
			if(role_id == 1) {
				this.roleType = ROLE_TYPE.ADMIN;
			} else {
				this.roleType = ROLE_TYPE.COMMON;
				if(shareId){//c端用户点击分享的话
					this.userId = shareId;
				}
			}
			this.currentPath = `/pages/product/detail?id=${this.baseId}&user_id=${this.userId}`;
			console.log('role_id2222',role_id,this.roleType)
			
			this.getDetail().then((res) => {
				
				if(this.roleType == ROLE_TYPE.ADMIN){
					this.getCollectStatus();
				}
				//这时详情接口已返回
				this.sendToServerOnShow(this.baseName, this.bgImage);
			})
			this.allFiledThrottle = throttle(this.allFiledChange,500);
			
		},
		created(){
			console.log('created productor detail')
			this.tabIntroduceVisible = false;
			this.tabNearbyVisible = false;
			this.tabTitleVisible = true;
			
		},
		onReady(){
			console.log('productor onReady',this.scrollFlag)
			const { windowHeight } = uni.getSystemInfoSync(); // 获取页面高度
			this.windowHeight = windowHeight;
			this.threshold = this.windowHeight / 2 - 20;
			// this.initInterSection();
			
		},
		onShow() {
			console.log('productor onShow')
		},
		mounted(){
			console.log('productor mounted',this)
			
			
			
		},
		onUnload(){
			
			console.log('onUnload')
		},
		beforeDestroy(){
			console.log('beforeDestroy')
		},
		destroyed(){
			console.log('destroyed')
		},
		onPageScroll(e){
			// console.log('eeeeeeeee',e)
			this.allFiledThrottle(e);
		},
		methods: {
			allFiledChange({scrollTop}){
				this.titleFieldChange(scrollTop);
				this.introduceFieldChange(scrollTop);
				this.nearByFieldChange(scrollTop)
				// console.log('222',scrollTop)
				
			},
			nearByFieldChange(scrollTop){
				uni.createSelectorQuery().select('.nearby-card').boundingClientRect((res)=>{
					console.log('tittitititi',res)
					let selfTop = res.top;
					let selfBottom = res.bottom;
					let thresholdTop = this.threshold;
					if(selfTop < thresholdTop && selfBottom +10 > thresholdTop){
						if(this.scrollFlag){
							return;
						}
						// if(this.feature){
						this.current = 2;
						this.tabNearbyVisible = true;
						
					} else {
						this.tabNearbyVisible = false;
					}
					this.tabVisible = this.current == 1 || this.current == 2;
					// this.tabVisible = this.tabIntroduceVisible || this.tabNearbyVisible;
					console.log('2',this.tabIntroduceVisible,this.tabNearbyVisible,this.tabVisible,this.current)
				}).exec()
				
			},		
			introduceFieldChange(scrollTop){
				uni.createSelectorQuery().select('.introduce-card').boundingClientRect((res)=>{
					console.log('tittitititi',res)
					let selfTop = res.top;
					let selfBottom = res.bottom;
					let thresholdTop = this.threshold;
					if(selfTop < thresholdTop && selfBottom +10 > thresholdTop){
						if(this.scrollFlag){
							return;
						}
						// if(this.feature){
						this.current = 1;
						this.tabIntroduceVisible = true;
						
					} else {
						this.tabIntroduceVisible = false;
					}
					this.tabVisible = this.current == 1 || this.current == 2;
					// this.tabVisible = this.tabIntroduceVisible || this.tabNearbyVisible;
					console.log('1',this.tabIntroduceVisible,this.tabNearbyVisible,this.tabVisible,this.current)
				}).exec()
			},
			titleFieldChange(scrollTop){
				
				uni.createSelectorQuery().select('.title-card').boundingClientRect((res)=>{
					console.log('tittitititi',res)
					let selfTop = res.top;
					let selfBottom = res.bottom;
					let thresholdTop = this.threshold;
					if(selfTop < thresholdTop && selfBottom +10 > thresholdTop){
						if(this.scrollFlag){
							return;
						}
						// if(this.feature){
						this.current = 0;
						this.tabTitleVisible = true;
						
					} else {
						this.tabTitleVisible = false;
					}
					this.tabVisible = this.current == 1 || this.current == 2;
					// this.tabVisible = this.tabIntroduceVisible || this.tabNearbyVisible;
					console.log('0',this.tabIntroduceVisible,this.tabNearbyVisible,this.tabVisible,this.current)
				}).exec()
			},
			videoErrorCallback: function(e) {
				console.log('videoshibai')
					uni.showModal({
						content: e.target.errMsg,
						showCancel: false
					})
			},
			getDetail(){
				
				return new Promise((resolve,reject) =>{
					this.$http.get(`/api/business/product/view/${this.baseId}`,{is_user:1,user_id:this.userId}).then((res) => {
						let result = res.data;
						if(result.status == 200) {
							this.palceId = result.data.id;
							console.log('jidi',res.data);
							this.bgImage =result.data.picture;
							this.baseName = result.data.title;
							this.typeName = result.data.category.title;
							this.description = result.data.description;
							this.moduleData = result.data.label;
							this.videoUrl = result.data.video;
							this.content = result.data.detail&&result.data.detail.content||'';
							this.shortTitle = result.data.short_title;
							this.feature = result.data.feature;
							
							this.contactInfo.name = result.data.user.nickname;
							this.contactInfo.imgUrl = result.data.user.avatar;
							this.contactInfo.position = result.data.user.detail.position;
							this.contactInfo.phone = result.data.user.username;
							resolve()
						}
					})
				})
				
			},
			getCollectStatus(){
				let data = {
					product_id:this.palceId,
					
				}
				this.$http.get('/api/member/business/collect/product/status',data).then((res) => {
					if(res.data.status == 200){
						this.collectStatus = res.data.data;
						
						if(this.collectStatus){
							this.navOptions[0].imgUrl = '/static/icon/collect-fill.png';
							this.navOptions[0].icon = 'star-fill';
							this.navOptions[0].text = '已收藏';
							console.log('已收藏啊')
						} else {
							this.navOptions[0].imgUrl = '/static/icon/collect.png';
							this.navOptions[0].icon = 'star';
							this.navOptions[0].text = '收藏'
						}
						
					}
					
				})
			},
			onOptionClick(index) {
				console.log('onOptionClick',index)
				if(index == 0) {
					//收藏
					this.collect();
				} else if(index == 1) {
					//标注
					this.$Router.push({name:'productLabel',query:{img:this.bgImage,title:this.baseName,product_id:this.palceId}});
				} else if(index == 2) {
					this.addShop();
				}
			},
			onButtonClick(index){
				console.log('onButtonClick',index)
				if(index == 0){//海报
					this.$Router.push({name:'productPoster',query:{product_id:this.palceId}});
					
				} else {//分享
					this.$refs.share.open(this.bgImage);
					const data = {
						product_id:this.palceId,
						path:this.currentPath
					}
					this.$http.post('/api/member/business/share/product/handle',data).then((res) => {
						
					})
				}
				
			},
			addShop(){
				let data = {
					product_id:this.palceId,
					
				}
				
				this.$http.post('/api/member/business/cart/handle',data).then((res) => {
					
					if(res.data.status == 200) {
						this.$tip.success('加入购物车成功')
						
					} else {
						
					}
				})
			},
			collect(){
				let data = {
					product_id:this.palceId,
					
				}
				
				this.$http.post('/api/member/business/collect/product/handle',data).then((res) => {
					
					if(res.data.status == 200) {
						
						if(!this.collectStatus){
							this.collectStatus = true;
							this.$tip.success('收藏成功')
							this.navOptions[0].icon = 'star-fill';
							this.navOptions[0].imgUrl = '/static/icon/collect-fill.png';
							this.navOptions[0].text = '已收藏'
						} else {
							this.collectStatus = false;
							this.$tip.success('取消收藏')
							this.navOptions[0].icon = 'star';
							this.navOptions[0].imgUrl = '/static/icon/collect.png';
							this.navOptions[0].text = '收藏'
						}
					} else {
						
					}
				})
				
			},
			goBack(){
				uni.navigateBack(-1)
			},
			locationTo() {
				
				this.$Router.push({name:'map',query:{
					longitude:this.longitude,
					latitude: this.latitude,
					placeName:this.baseName,
					detailAddress:this.detailAddress}})
			},
			routeToBase(item){
				this.$Router.push({name:'baseResourceDetail',query:{id:item.id}})
			},
			changeTab(index){
				
				let offetHeight = this.windowHeight/2;
				// if(index > this.current){
				// 	//向下
				// 	offetHeight = 50;
				// } else {
				// 	offetHeight = -50;
				// }
				this.current = index;
				let className = '';
				if(index == 0){
					className = '.title-card';
				}else if(index == 1) {
					className = '.introduce-card';
				} else {
					className = '.nearby-card';
				}
				uni.createSelectorQuery()
				.select(className)
				.boundingClientRect((con) => {
				  console.log(con,className);
				  // 获取点击要跳转的锚点信息
				  uni
					.createSelectorQuery()
					.select(".base-resource-detail")
					.boundingClientRect((res) => {
					  // console.log(res);
					  console.log(con.top - res.top,res);
					  let scrollTop = 0;
					 
					 scrollTop = con.top - res.top - this.windowHeight + offetHeight + 50;
					 // < 0 ?0 : con.top - res.top - windowHeight;
					  // console.log('dcrooltp',con.top - res.top - windowHeight,scrollTop)
					  // 获取根元素要滑动的元素
					  uni.pageScrollTo({
						// selector: className, // 滑动的元素
						// duration: 1500, // 过渡时间
						scrollTop: scrollTop, // 到达距离顶部的top值
					  });
					  this.scrollFlag = true;
					  if(this.current == 0){
					  	this.tabVisible = false;
					  }
					  setTimeout(()=>{
						  console.log('wwwww',scrollTop)
						  this.scrollFlag = false;
					  },600)
					})
					.exec();
				})
				.exec();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.base-resource-detail{
		background-color: #F1F2F4;
		min-height: 100vh;
		.left-icon{
			position: fixed;
			
			z-index:1;
		}
		.top-operate{
			position: fixed;
			
			z-index:1;
			width: 100%;
		}
		.top-operate-tab{
			height: 128rpx;
			width: 100%;
			// display: flex;
			position: fixed;
			background-color: #fff;
			// border-bottom: 2rpx solid #EFEFEF;
			// display: flex;
			// justify-content: space-around;
			// align-items: center;
			// .active-style{
			// 	color: #EE8731;
			// }
		}
		.title-picture{
			// height: 750rpx;
			width:100%;
		}
		.custom-tabbar-page{
			padding-bottom: calc(112rpx + env(safe-area-inset-bottom));
			// height: calc(100vh - 112rpx - env(safe-area-inset-bottom) / 2);
			.body-field{
				margin-left: 30rpx;
				margin-right: 30rpx;
				position: relative;
				top:-36rpx;
				.text-style{
					background-color: #F5F6F8;
					font-size: 32rpx;
					line-height: 60rpx;
					color: #656668;
				}
				.title-card{
					width: 690rpx;
					
					background-color: #FFFFFF;
					border-radius: 10rpx;
					
					position: relative;
					margin-bottom:30rpx;
					
					.name-field{
						padding-top:60rpx;
						display: flex;
						justify-content: space-between;
					}
					.name{
						
						flex:1;
						padding-left: 20rpx;
						word-wrap:break-word;
						word-break: break-all;
						font-size: 56rpx;
						line-height: 62rpx;
						color:#616571;
						font-weight: $Semibold;
						
						
					}
					.right-type{
						
						margin-left: 86rpx;
						padding: 0 20rpx;
						
						height: 62rpx;
						background-color: #485160;
						color: #FFFFFF;
						font-size: 28rpx;
						font-weight: $Semibold;
						display: flex;
						justify-content: center;
						align-items: center;
						border-top-left-radius: 10rpx;
						border-bottom-left-radius: 10rpx;
						text{
							margin-left: 18rpx ;
						}
						image{
							width: 36rpx;
							height: 26rpx;
						}
					}
					
					.detail-field{
						padding:38rpx 30rpx 30rpx;
						.video{
							margin-bottom: 20rpx;
							video{
								width: 100%;
							}
						}
						.sort-title{
							margin-bottom: 20rpx;
							font-size: 56rpx;
							color:orange;
							text-align: center;
						}
						.text-field{
							margin-bottom: 20rpx;
							padding:30rpx 26rpx 30rpx 30rpx;
							
						}
						.module-field{
							display: grid;
							grid-template-columns: auto auto auto;
							grid-gap: 12rpx;
							.module-item{
								color:#656668;
								background-color: #F7F8FC;
								text-align: center;
								// width: 220rpx;
								height: 54rpx;
								line-height: 54rpx;
							}
							
						}
					}
				}
				.introduce-card{
					background-color: #FFFFFF;
					padding:0 30rpx 30rpx;
					margin-bottom: 30rpx;
					border-radius: 10rpx;
					
					.text-field{
						
						padding:30rpx 24rpx 30rpx 30rpx;
						
					}
				}
				.title{
					padding:80rpx 0;
					font-size: 56rpx;
					color: #4C5059;
					font-weight: $Semibold;
					text-align: center;
					&:before{
						content: '1';
						color: transparent;
						
						width: 40rpx;
						height: 40rpx;
						background: url("/static/product/text-left.png") no-repeat ;
						background-size: 100%;
						background-position: center;
						margin-right: 26rpx;
					}
					&:after{
						content: '2';
						color: transparent;
						width: 40rpx;
						height: 40rpx;
						background: url("/static/product/text-right.png") no-repeat;
						background-size: 100%;
						background-position: center;
						margin-left: 26rpx;
					}
					
				}
				.nearby-card{
					background-color: #FFFFFF;
					padding:0rpx 40rpx 30rpx;
					
					
					
				}
			}
		}
	}

</style>
